//
//  NetWorkTools.m
//  AIM
//
//  Created by user10 on 2017/6/5.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "NetWorkTools.h"

@implementation NetWorkTools

static NetWorkTools *tools;

+ (instancetype)shareTools{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        tools =[[self alloc]init];
        tools.responseSerializer = [AFXMLParserResponseSerializer serializer];
        // 设置请求超时时间
        tools.requestSerializer.timeoutInterval = 1;
        // 返回NSData
        tools.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 设置请求头，也可以不设置
        [tools.requestSerializer setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    });
    
    return tools;
}


- (void)request:(AIMRequestMethod)method urlString:(NSString *)urlString parametersStr:(NSString *)parametersStr finished:(void (^)(id responseObject,NSError *error))finished;{
    
    NSString *tempStr = [NSString stringWithFormat:
                         @"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.com/\">\
                         <soapenv:Header/>\
                         <soapenv:Body>\
                         %@\
                         </soapenv:Body>\
                         </soapenv:Envelope>",parametersStr];
    
    [tools.requestSerializer setValue:[NSString stringWithFormat:@"%zd", tempStr.length] forHTTPHeaderField:@"Content-Length"];
    // 设置HTTPBody
    [tools.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error)
     {
         return tempStr;
     }];

    if (method ==GET) {
        
        [self GET:urlString parameters:parametersStr success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            finished(responseObject,nil);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            finished(nil,error);
        }];
        
    }else{
        
        [self POST:urlString parameters:parametersStr success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            finished(responseObject,nil);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            finished(nil,error);
        }];
        
        
    }
    
}
@end
